package org.beholder;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

public class ImageServlet extends AbstractServlet {

	Logger logger = Logger.getLogger(ImageServlet.class);
	
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	String id = req.getParameter("id");
    	InputStream is = getImageStream(id);
    	OutputStream os = resp.getOutputStream();
    	IOUtils.copy(is, os);
    	IOUtils.closeQuietly(is);
    	IOUtils.closeQuietly(os);
    }
    
    private InputStream getImageStream(String id) {
    	InputStream is = null;
    	try {
    		PreparedStatement ps = conn.prepareStatement("SELECT image FROM shots_tbl WHERE id=?");
    		ps.setLong(1, Long.parseLong(id));
    		ResultSet rs = ps.executeQuery();
    		rs.next();
    		is = rs.getBinaryStream(1);
    	} catch (SQLException e) {
    		logger.error(e, e);
    	}
    	return is;	
    }

}
